import './index.css'; // 导入你的 CSS 文件
console.log('chatJs run.');
let userName = "";

let initChatList = [];

let userList = [];
let chatList = [];

let socket;
const textAreaEle = document.getElementById('chatInputId');
const chatListEle = document.getElementById('chatListId')


userName = prompt("请输入你的名字：");
do {
    if (userName !== null && userName.trim() !== "") {
        console.log('已获取到名字');
        localStorage.setItem('userName', userName)
    } else {
        userName = prompt("请输入你的名字哦：");
    }
} while (userName === null || userName.trim() === "");

alert("你好，" + userName);











if ("WebSocket" in window) {
    socket = new WebSocket("ws://192.168.5.78:8888"); //直接写路径
    // socket.onerror = webSocketOnError;
    socket.onmessage = webSocketOnMessage;
    // socket.onclose = closeWebsocket;
    socket.onopen = openWebsocket;
} else {
    alert("错误,您的浏览器不支持websocket，请更换Chrome或者Firefox");
}

// 输入框
textAreaEle.addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
        if (!event.shiftKey) {
            event.preventDefault()
            sendMessage()
        }
    }
})
// 回车发送
function sendMessage() {
    if (textAreaEle.value.trim() === '') return
    const content = textAreaEle.value;
    console.log('content:', JSON.stringify(content));
    textAreaEle.value = ''
    const time = getFormattedTime()
    console.log(time);
    const params = {
        type: 1,
        message: content,
        time
    }
    socket.send(JSON.stringify(params))
}

function getFormattedTime() {
    const now = new Date();
    const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
    return now.toLocaleString('zh-CN', options);
}



//建立连接
function openWebsocket(e) {
    console.log('open success!');
    if (e.currentTarget.readyState === 1) {
        const message = JSON.stringify({
            userName,
            type: 0,
            status: 0
        })
        socket.send(message)
    }
}

// 接收消息
function webSocketOnMessage(e) {
    console.log('webSocketOnMessage e =>', e.data);
    const data = JSON.parse(e.data)
    if (data.type === 0) {
        chatList.push(data)
    }
    console.log('chatList', chatList);
    const elements = chatList.map(item => `<li class="${item.type === 0 ? 'system-info' : ''}">
        ${item.type === 0 ?
            `<span title="${item.userName}来了">${item.userName}来了</span>` :
            `
            
            `
        }
        </li>`);
}